package edu.lingnan.exception;

import com.baomidou.mybatisplus.extension.api.R;
import edu.lingnan.vo.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExceptionControllerAdvice
 * @Description TODO
 * @Author kang
 * @Date 2022/9/14 下午 9:04
 * @Version 1.0
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {
    /**
     * 处理特定异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach((fieldError -> {
                String field = fieldError.getField();
                String message = fieldError.getDefaultMessage();
                map.put(field, message);
            }));
        }
        return new Result(false, map, "数据校验不通过");
    }

    @ExceptionHandler(value = IOException.class)
    public Result handleIOException(){
        return new Result(false, null, "服务器解析图片异常,请联系管理员");
    }



    // @ExceptionHandler(value = NoLoginException.class)
    // public Result handleNoLoginException(NoLoginException noLoginException){
    //     return new Result(false, null, noLoginException.getMessage());
    // }


    /**
     * 处理其他异常
     *
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        return new Result(false, null, "服务器内部出现错误，请反馈给管理员！");
    }

}
